import pygame
import sys

speeds = {pygame.K_LEFT: [-20, 0], pygame.K_RIGHT: [20, 0],
          pygame.K_UP: [0, -20], pygame.K_DOWN: [0, 20]}


class Sigma(pygame.sprite.Sprite):
    def __init__(self, src, size, location=[0,0]):
        pygame.sprite.Sprite.__init__(self)
        self.width = size[0]
        self.height = size[1]
        self.images = pygame.image.load(src)
        self.image_num = 0
        self.image_max = int(self.images.get_width() / self.width) - 1
        self.rect = self.images.get_rect()
        self.image = None
        self.last_time = 0
        self.moving(location)

    def update(self, *args, **kwargs) -> None:
        if args[0] > self.last_time + 90:
            self.last_time = args[0]
            if self.image_num >= self.image_max:
                self.image_num = 0
            else:
                self.image_num += 1

            self.image = self.images.subsurface((self.width * self.image_num, 0, self.width, self.height))

    def moving(self, speed):
        if speed:
            self.rect = self.rect.move(speed)


def main():
    pygame.init()
    size = width, height = 640, 480
    screen = pygame.display.set_mode(size)
    # 设置标题
    pygame.display.set_caption("Sigma Sprite")
    color = (0, 0, 0)
    clock = pygame.time.Clock()

    sigma = Sigma("../res/image/cry_running.png", [100, 100])
    sigmas = pygame.sprite.Group()
    sigmas.add(sigma)

    pterosaur = Sigma("../res/image/pterosaur.png", [190, 180], [400, 300])
    sigmas.add(pterosaur)

    while True:
        clock.tick(60)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                sigma.moving(speeds.get(event.key))

        screen.fill(color)
        sigmas.update(pygame.time.get_ticks())
        sigmas.draw(screen)
        pygame.display.update()

    pygame.quit()


if __name__ == '__main__':
    main()

